<template>
  <div class="monitoring-container">
    <h1>设备状态监控和统计分析</h1>

    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #409eff;">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.total }}</div>
              <div class="stat-label">设备总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #67c23a;">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.normal }}</div>
              <div class="stat-label">正常运行</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.maintenance }}</div>
              <div class="stat-label">维修中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.scrap }}</div>
              <div class="stat-label">已报废</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>设备状态分布</span>
            </div>
          </template>
          <div ref="statusChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>设备类型分布</span>
            </div>
          </template>
          <div ref="typeChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="query" label-width="80px" inline>
        <el-form-item label="设备名称">
          <el-input v-model="query.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="正常"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="已报废" value="已报废"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchEquipment">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 设备表格 -->
    <el-table
        :data="pagedData"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="设备名称" width="150" />
      <el-table-column prop="model" label="设备型号" width="150" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="purchase_date" label="购买日期" width="120" />
      <el-table-column prop="last_maintenance_date" label="最后维护日期" width="120" />
      <el-table-column prop="location" label="位置" width="120" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="viewDetails(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="tableData.length > 0"
        background
        layout="prev, pager, next, sizes, total"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="tableData.length"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; justify-content: center;"
    />

    <!-- 设备详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="设备详情"
        width="600px"
    >
      <el-form
          :model="detailForm"
          label-width="100px"
          disabled
      >
        <el-form-item label="设备名称">
          <el-input v-model="detailForm.name" />
        </el-form-item>
        <el-form-item label="设备型号">
          <el-input v-model="detailForm.model" />
        </el-form-item>
        <el-form-item label="状态">
          <el-input v-model="detailForm.status" />
        </el-form-item>
        <el-form-item label="购买日期">
          <el-input v-model="detailForm.purchase_date" />
        </el-form-item>
        <el-form-item label="最后维护日期">
          <el-input v-model="detailForm.last_maintenance_date" />
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="detailForm.location" />
        </el-form-item>
        <el-form-item label="部门ID">
          <el-input v-model="detailForm.department_id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import {
  Monitor,
  Check,
  Warning,
  CircleClose
} from '@element-plus/icons-vue';
import equipmentApi from '../api/equipmentApi.js';

// 数据状态
const tableData = ref([]);
const loading = ref(false);
const detailDialogVisible = ref(false);
const statusChart = ref(null);
const typeChart = ref(null);
let statusChartInstance = null;
let typeChartInstance = null;

// 分页参数
const page = ref(1);
const pageSize = ref(10);

// 计算分页数据
const pagedData = computed(() => {
  if (!Array.isArray(tableData.value)) {
    return [];
  }
  const start = (page.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 查询条件
const query = reactive({
  name: '',
  status: ''
});

// 详情表单
const detailForm = reactive({
  id: null,
  name: '',
  model: '',
  status: '',
  purchase_date: '',
  last_maintenance_date: '',
  location: '',
  department_id: null
});

// 统计数据
const statistics = reactive({
  total: 0,
  normal: 0,
  maintenance: 0,
  scrap: 0
});

// 获取状态标签类型
const getTagType = (status) => {
  switch (status) {
    case '正常':
      return 'success';
    case '维修中':
      return 'warning';
    case '已报废':
      return 'danger';
    default:
      return 'info';
  }
};

// 加载设备列表
const loadEquipment = async () => {
  loading.value = true;
  try {
    const res = await equipmentApi.list();
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : [];
      calculateStatistics(tableData.value);
      await nextTick();
      renderCharts();
    } else {
      tableData.value = [];
      ElMessage.error(res?.msg || '数据加载失败');
    }
  } catch (err) {
    console.error('加载设备列表失败:', err);
    tableData.value = [];
    ElMessage.error('加载设备列表失败: ' + (err.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 计算统计数据
const calculateStatistics = (data) => {
  statistics.total = data.length;
  statistics.normal = data.filter(item => item.status === '正常').length;
  statistics.maintenance = data.filter(item => item.status === '维修中').length;
  statistics.scrap = data.filter(item => item.status === '已报废').length;
};

// 渲染图表
const renderCharts = () => {
  // 销毁已有的图表实例
  if (statusChartInstance) {
    statusChartInstance.dispose();
  }
  if (typeChartInstance) {
    typeChartInstance.dispose();
  }
  
  // 设备状态分布图
  if (statusChart.value) {
    statusChartInstance = echarts.init(statusChart.value);
    const statusOption = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: '设备状态',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: statistics.normal, name: '正常' },
            { value: statistics.maintenance, name: '维修中' },
            { value: statistics.scrap, name: '已报废' }
          ]
        }
      ]
    };
    statusChartInstance.setOption(statusOption);
  }

  // 设备类型分布图（模拟数据）
  if (typeChart.value) {
    typeChartInstance = echarts.init(typeChart.value);
    const typeOption = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: '设备类型',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 15, name: '生产设备' },
            { value: 8, name: '检测设备' },
            { value: 5, name: '辅助设备' },
            { value: 12, name: '其他设备' }
          ]
        }
      ]
    };
    typeChartInstance.setOption(typeOption);
  }
};

// 查询设备
const searchEquipment = async () => {
  loading.value = true;
  try {
    const res = await equipmentApi.list(query);
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : [];
      calculateStatistics(tableData.value);
      await nextTick();
      renderCharts();
    } else {
      tableData.value = [];
      ElMessage.error(res?.msg || '查询失败');
    }
    page.value = 1;
  } catch (err) {
    console.error('查询设备失败:', err);
    tableData.value = [];
    ElMessage.error('查询设备失败: ' + (err.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 重置查询
const resetSearch = () => {
  query.name = '';
  query.status = '';
  loadEquipment();
};

// 分页事件处理
const handlePageChange = (newPage) => {
  page.value = newPage;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  page.value = 1;
};

// 查看详情
const viewDetails = (equipment) => {
  Object.assign(detailForm, equipment);
  detailDialogVisible.value = true;
};

// 窗口大小变化处理
const handleResize = () => {
  if (statusChartInstance) {
    statusChartInstance.resize();
  }
  if (typeChartInstance) {
    typeChartInstance.resize();
  }
};

// 初始化加载数据
onMounted(() => {
  loadEquipment();
  window.addEventListener('resize', handleResize);
});

// 组件卸载前清理
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  if (statusChartInstance) {
    statusChartInstance.dispose();
  }
  if (typeChartInstance) {
    typeChartInstance.dispose();
  }
});
</script>

<style scoped>
.monitoring-container {
  padding: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.stat-icon i {
  font-size: 30px;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #999;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}
</style>